sap.ui.define([
	"sap/ui/core/mvc/Controller",
	"firorworkshop185/model/formatter",
	"sap/m/Button"
], function (
	Controller,
	formatter,
	Button
) {
	"use strict";

	return Controller.extend("firorworkshop185.controller.OrderList", {
		formatter: formatter,

		onInit: function () {
			// 在控制器中定义全局变量
			// this.sFragmentId = "";
			var oEventBus = sap.ui.getCore().getEventBus();
			// 订阅事件
			oEventBus.subscribe("overViewEventChannel", "initTable", this.onEventTriggered, this);
			// 隧道里带参数的情况
			oEventBus.subscribe("overViewEventChannel", "initIconTabBar", (channel, event, data) => {
				this.initIconTabBar(data);
			}, this);
			// 这里前两个参数可以是任意的字符串
			// 只要在调用的地方使用sap.ui.getCore().getEventBus().publish()的时候往里传入的参数一致即可

			this.orderTableList = [];
		},

		onEventTriggered: function (sChannel, sEvent, oData) {
			// 在事件发生时执行的方法
			// var eventData = oData.data;
			this.initTable()
			// 执行相应的逻辑
		},

		initTable() {
			// oData里的数据是对象，这里先将其转化为列表
			let sourceList = formatter.objectTransformToList(this.getView().getModel("ENTITY001Set"));

			// 从oData里取到的数据列表里的每个对象有些属性的类型是对象
			// 但因为我们这里要显示在table里，所以要过滤掉这些类型为对象的属性
			// 其中日期对象我们将其手动转化为字符串，null对象手动将其转化为空字符串
			let sourceListWithoutObject = formatter.removeNestedObjects(sourceList);
			// 此时列表中所有对象的属性都一样了
			this.orderTableList = sourceListWithoutObject;
			this.initIconTabBar(sourceListWithoutObject);

			// 在本地json那里设置默认可见的列
			// 然后将其余列设置为默认不可见
			var oModel = this.getView().getModel('info');
			let Obj = oModel.oData.order;
			oModel.setData({
				...oModel.oData,
				order: Obj
			});
			let list = Object.keys(sourceListWithoutObject[0]);
			list.forEach(element => {
				if (!Obj[element]) {
					Obj[element] = {
						text: element,
						ifShow: false,
						ifSort: false
					}
				}
			});
			oModel.setData({
				...oModel.oData,
				order: Obj
			});


			var oTable = this.getView().byId("ordersTable");
			oTable.removeAllColumns();

			list.forEach(element => {
				var oColumn = new sap.m.Column({
					header: new sap.m.Text({ text: this.getView().getModel('info').oData.order[element].text }),
					visible: {
						path: "info>/order/" + element + "/ifShow"
					}
				});
				oTable.addColumn(oColumn);
			});

			// sourceListWithoutObject.forEach(element => {
			// 	let cellList = [];
			// 	list.forEach(keyElement => {
			// 		cellList.push(new sap.m.Text({ text: element[keyElement] }));
			// 	});
			// 	var oItem = new sap.m.ColumnListItem({ cells: cellList });
			// 	oTable.addItem(oItem);
			// });

			// 最好不用上面的方法一个一个单独创建
			// 而是用下面这个方法对数据进行绑定，方便table的筛选功能
			var oModel = new sap.ui.model.json.JSONModel({
				items: sourceList
			}, "orderList");
			oTable.setModel(oModel);
			let cell = [];
			let dateList = ["issDate", "dateFrom", "dateTo"];
			list.forEach(element => {
				if (element != "orderNo") {
					if (dateList.indexOf(element) != -1) {
						cell.push(new sap.m.Text({
							text: {
								path: element,
								formatter: formatter.transformDate
							}
						}));
					} else {
						cell.push(new sap.m.Text({
							text: "{" + element + "}"
						}));
					}
				} else {
					cell.push(new sap.m.Link({
						text: "{" + element + "}",
						// press: "goDetail"
						href: "#/detail/" + "{" + element + "}",
					}));
				}
			});
			oTable.setModel(oModel);

			oTable.bindItems("/items", new sap.m.ColumnListItem({
				cells: cell
			}));

			var oTitle = new sap.m.Title({
				level: "H2",
				text: {
					parts: ["/items"],
					formatter: function (items) {
						return "Orders (" + (items ? items.length : 0) + ")";
					}
				}
			});

			let contentList1 = [oTitle]
			let contentList2 = oTable.getHeaderToolbar().mAggregations.content;
			let mergeContentList = []
			if (contentList2.length == 4) {
				mergeContentList = contentList1.concat(contentList2);
			} else {
				mergeContentList = contentList1.concat(contentList2.slice(1, 5));
			}

			// 创建OverflowToolbar并添加Title组件
			var oToolbar = new sap.m.OverflowToolbar({
				content: mergeContentList
			});

			oTable.setHeaderToolbar(oToolbar);

			this.doFilterTable();
			var oEventBus = sap.ui.getCore().getEventBus();
			oEventBus.publish("overViewEventChannel", "goSearchPress");
			this.doSortTable();

			var oModel = this.getView().getModel('info');
			oModel.setData({
				...oModel.oData,
				getOrderCompleted: true
			});
		},

		initIconTabBar(list) {
			var oIconTabFilterAll = this.getView().byId("IconTabFilterAll");
			oIconTabFilterAll.setCount(list.length);
			var oIconTabFilterNEW = this.getView().byId("IconTabFilterNEW");
			oIconTabFilterNEW.setCount(list.filter(element => element.statusNo == "NEW").length);
			var oIconTabFilterREPAIRED = this.getView().byId("IconTabFilterREPAIRED");
			oIconTabFilterREPAIRED.setCount(list.filter(element => element.statusNo == "REPAIRED").length);
			var oIconTabFilterCLOSED = this.getView().byId("IconTabFilterCLOSED");
			oIconTabFilterCLOSED.setCount(list.filter(element => element.statusNo == "CLOSED").length);
			var oIconTabFilterDELETED = this.getView().byId("IconTabFilterDELETED");
			oIconTabFilterDELETED.setCount(list.filter(element => element.statusNo == "DELETED").length);

			// var oIconTabBar = this.getView().byId("idIconTabBar");
			// oIconTabBar.removeAllItems();
			// oIconTabBar.addItem(new sap.m.IconTabFilter({
			// 	icon: "sap-icon://notes",
			// 	count: this.orderTableList.length,
			// 	text: "All",
			// 	key: "All"
			// }));
			// oIconTabBar.addItem(new sap.m.IconTabFilter({
			// 	icon: "sap-icon://home",
			// 	iconColor: "Negative",
			// 	count: this.orderTableList.filter(element => element.statusNo == "NEW").length,
			// 	text: "NEW",
			// 	key: "NEW"
			// }));
			// oIconTabBar.addItem(new sap.m.IconTabFilter({
			// 	icon: "sap-icon://inventory",
			// 	iconColor: "Critical",
			// 	count: this.orderTableList.filter(element => element.statusNo == "REPAIRED").length,
			// 	text: "REPAIRED",
			// 	key: "REPAIRED"
			// }));
			// oIconTabBar.addItem(new sap.m.IconTabFilter({
			// 	icon: "sap-icon://complete",
			// 	iconColor: "Positive",
			// 	count: this.orderTableList.filter(element => element.statusNo == "CLOSED").length,
			// 	text: "CLOSED",
			// 	key: "CLOSED"
			// }));
			// oIconTabBar.addItem(new sap.m.IconTabFilter({
			// 	icon: "sap-icon://delete",
			// 	count: this.orderTableList.filter(element => element.statusNo == "DELETED").length,
			// 	text: "DELETED",
			// 	key: "DELETED"
			// }));
		},

		/**
		 * 控制table需要显示哪一列的dialog
		 */
		showViewSetting() {
			var oView = this.getView();
			if (!this.viewSettingDialog) {
				this.viewSettingDialog = this.loadFragment({
					name: "firorworkshop185.view.fragment.ViewSetting",
					controller: this
				}).then(function (oValueHelpDialog) {
					oView.addDependent(oValueHelpDialog);
					return oValueHelpDialog;
				});
			}
			this.viewSettingDialog.then(function (oValueHelpDialog) {
				oValueHelpDialog.open();
			});
		},

		onKeyTableDialogCancel() {
			sap.ui.core.Fragment.byId(this.getView().getId(), "viewSettingDialog").close();
		},

		onKeyTableDialogConfirm() {
			var oTable = sap.ui.core.Fragment.byId(this.getView().getId(), "KeyTable");
			oTable.closeViewSettingDialog();
			sap.ui.core.Fragment.byId(this.getView().getId(), "viewSettingDialog").close();
		},
		/**
		 * 控制table需要显示哪一列的dialog结束
		 */

		/**
		 * 控制table按哪一列排序的dialog
		 */
		showSortSetting() {
			var oView = this.getView();
			if (!this.sortSettingDialog) {
				this.sortSettingDialog = this.loadFragment({
					name: "firorworkshop185.view.fragment.SortSetting",
					controller: this
				}).then(function (oValueHelpDialog) {
					oView.addDependent(oValueHelpDialog);
					return oValueHelpDialog;
				});
			}
			this.sortSettingDialog.then(function (oValueHelpDialog) {
				oValueHelpDialog.open();
			});
		},

		onSortTableDialogCancel() {
			sap.ui.core.Fragment.byId(this.getView().getId(), "sortSettingDialog").close();
		},

		onSortTableDialogConfirm() {
			var oTable = sap.ui.core.Fragment.byId(this.getView().getId(), "SortTable");
			oTable.closeSortSettingDialog();
			this.doSortTable();
			sap.ui.core.Fragment.byId(this.getView().getId(), "sortSettingDialog").close();
		},

		doSortTable() {
			let sortList = [];
			Object.keys(this.getView().getModel("info").oData.order).forEach(element => {
				if (this.getView().getModel("info").oData.order[element].ifSort) {
					sortList.push(new sap.ui.model.Sorter(element, false));
					// false表示升序,true表示降序
				}
			});
			var oTable = this.getView().byId("ordersTable");

			var oBinding = oTable.getBinding("items");
			oBinding.sort(sortList);
		},

		/**
		 * 控制table按哪一列排序的dialog结束
		 */

		/**
		 * 控制点击IconFilterBar或输入筛选的方法
		 */

		doFilterTable() {
			var oTable = this.getView().byId("ordersTable");
			var oIconTabBar = this.getView().byId("idIconTabBar");
			var oBinding = oTable.getBinding("items");
			var aFilters = oBinding.aFilters;

			let alreadyFilterList = formatter.objectTransformToList(aFilters);

			if (oIconTabBar.getSelectedKey() != "All" && oIconTabBar.getSelectedKey() != "") {
				alreadyFilterList[0] = new sap.ui.model.Filter("statusNo", sap.ui.model.FilterOperator.EQ, oIconTabBar.getSelectedKey());
			} else {
				alreadyFilterList[0] = new sap.ui.model.Filter("statusNo", sap.ui.model.FilterOperator.Contains, "");
			}

			oBinding.filter(alreadyFilterList);
		},

		onFilterSelect(oEvent) {
			var oTable = this.getView().byId("ordersTable");
			var oBinding = oTable.getBinding("items");
			var aFilters = oBinding.aFilters;

			let alreadyFilterList = formatter.objectTransformToList(aFilters);

			if (oEvent.mParameters.selectedKey != "All") {
				alreadyFilterList[0] = new sap.ui.model.Filter("statusNo", sap.ui.model.FilterOperator.EQ, oEvent.mParameters.selectedKey);
			} else {
				alreadyFilterList[0] = new sap.ui.model.Filter("statusNo", sap.ui.model.FilterOperator.Contains, "");
			}

			oBinding.filter(alreadyFilterList);

			// 变化title上的数据总数
			var oTitle = oTable.getHeaderToolbar().mAggregations.content[0];
			oTitle.setText("Orders (" + (oTable.getBinding("items").getLength() || 0) + ")");
		},

		/**
		 * 控制点击IconFilterBar或输入筛选的方法结束
		 */

		// 跳转到创建新的Order页
		createOrder() {
			const oRouter = this.getOwnerComponent().getRouter();
			oRouter.navTo("CreateOrder");
		}
	});
});